package com.xyz.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xyz.gulimall.product.entity.CategoryBrandRelationEntity;
import com.xyz.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyz.common.utils.PageUtils;
import com.xyz.common.utils.Query;

import com.xyz.gulimall.product.dao.CategoryDao;
import com.xyz.gulimall.product.entity.CategoryEntity;
import com.xyz.gulimall.product.service.CategoryService;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

     @Override
     public PageUtils queryPage(Map<String, Object> params) {
              IPage<CategoryEntity> page = this.page(
                      new Query<CategoryEntity>().getPage(params),
                      new QueryWrapper<CategoryEntity>()
              );
              return new PageUtils(page);
     }

    @Override
    public List<CategoryEntity> listWithTree() {
         //1.查出所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //2.1 找到所有1级分类
        List<CategoryEntity> level1Menus = list.stream().filter(categoryEntity->
                categoryEntity.getParentCid()== 0
        ).map((menu) ->{
            //调用查询子菜单
            menu.setChildren(getChildrens(menu,list));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
         //TODO 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
         List<Long> list = new ArrayList<>();
        List<Long> parentPath = this.findParentPath(catelogId,list);
        //转换排序
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if(!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.update(new UpdateWrapper<CategoryBrandRelationEntity>().set("catelog_name",category.getName()).eq("catelog_id",category.getCatId()));
        }
    }

    private List<Long> findParentPath(Long catelogId,List<Long> list){
         //收集当前节点id
        list.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),list);
        }
        return list;
    }

    /**
     * 递归查找所有菜单的子菜单
     */
    public List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2.菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
         return children;
    }

}